package org.shj.activitidemo.controller;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.shj.activitidemo.service.LeaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;


/**
 * @author Shen Huang Jian
 * @date 2019/9/13
 */
@RestController
@RequestMapping("/leave")
public class LeaveController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    LeaveService leaveService;

    @GetMapping("/apply")
    public String apply(@RequestParam("user") String user, @RequestParam int days){
        leaveService.startProcess(user, days);
        return "applied";
    }

    @GetMapping("/myTasks/{user}")
    public List<Map<String, Object>> getTasks(@PathVariable String user){
        List<Task> tasks = taskService//与任务相关的Service
                .createTaskQuery()//创建一个任务查询对象
                .taskAssignee(user)
                .list();
        return convert(tasks); // 直接返回 tasks 会报错
    }

    @GetMapping("/managerTasks")
    public List<Map<String, Object>> getManagerTasks(){
        List<Task> tasks = taskService//与任务相关的Service
                .createTaskQuery()//创建一个任务查询对象
                .taskCandidateGroup("manager")
                .list();
        return convert(tasks);
    }

    @GetMapping("/bossTasks")
    public List<Map<String, Object>> getBossTasks(){
        List<Task> tasks = taskService//与任务相关的Service
                .createTaskQuery()//创建一个任务查询对象
                .taskCandidateGroup("boss")
                .list();
        return convert(tasks);
    }

    @GetMapping("/allTasks")
    public List<Map<String, Object>> getAllTasks(){
        List<Task> tasks = taskService//与任务相关的Service
                .createTaskQuery()//创建一个任务查询对象
                .list();
        return convert(tasks);
    }

    @GetMapping("/process")
    public String process(@RequestParam("userType") String userType,
                          @RequestParam("reject") String reject){
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup(userType)
                .list();
        if(CollectionUtils.isEmpty(tasks)){
            return "没有任务要处理";
        }
        System.out.println(userType + "的任务有：" + tasks.size() + " 个");
        Task task = tasks.get(0);
        //设置审批任务的执行人
        taskService.claim(task.getId(), userType);
        //taskService.delegateTask();

        Map<String, Object> params = new HashMap<>();
        params.put("reject", reject);
        taskService.complete(task.getId(), params);
        return "任务" + task.getId() + "(" + task.getName() +")已被处理";
    }

    @RequestMapping(value = "/image", method = RequestMethod.GET)
    public void image(HttpServletResponse response,
                      @RequestParam String processInstanceId) {
        try {
            InputStream is = getDiagram(processInstanceId);
            if (is == null)
                return;

            response.setContentType("image/png");

            BufferedImage image = ImageIO.read(is);
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);

            is.close();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public InputStream getDiagram(String processInstanceId) {
        //获得流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();
        String processDefinitionId = StringUtils.EMPTY;
        if (processInstance == null) {
            //查询已经结束的流程实例
            HistoricProcessInstance processInstanceHistory =
                    historyService.createHistoricProcessInstanceQuery()
                            .processInstanceId(processInstanceId).singleResult();
            if (processInstanceHistory == null)
                return null;
            else
                processDefinitionId = processInstanceHistory.getProcessDefinitionId();
        } else {
            processDefinitionId = processInstance.getProcessDefinitionId();
        }

        //使用宋体
        String fontName = "宋体";
        //获取BPMN模型对象
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
        //获取流程实例当前的节点，需要高亮显示
        List<String> currentActs = Collections.EMPTY_LIST;
        if (processInstance != null)
            currentActs = runtimeService.getActiveActivityIds(processInstance.getId());

        return processEngine.getProcessEngineConfiguration()
                .getProcessDiagramGenerator()
                .generateDiagram(model, "png", currentActs, new ArrayList<String>(),
                        fontName, fontName, fontName, null, 1.0);
    }

    private List<Map<String, Object>> convert(List<Task> tasks){
        List<Map<String, Object>> list = new ArrayList<>();
        if(CollectionUtils.isEmpty(tasks)){
            return list;
        }else{
            for(Task task : tasks){
                Map<String, Object> map = new HashMap<>();
                map.put("任务ID:", task.getId());
                map.put("任务的办理人:", task.getAssignee());
                map.put("任务的owner:", task.getOwner());
                map.put("任务名称:", task.getName());
                map.put("任务的创建时间:", task.getCreateTime());
                map.put("流程实例ID:", task.getProcessInstanceId());
                list.add(map);
            }
            return list;
        }
    }

    @RequestMapping(value = "/activitiDemo", method = RequestMethod.GET)
    public boolean startActivityDemo() {

        System.out.println("method startActivityDemo begin....");

        System.out.println("调用流程存储服务，查询部署数量："
                + repositoryService.createDeploymentQuery().count());


        Map<String, Object> map = new HashMap<String, Object>();
        map.put("apply", "zhangsan");
        map.put("approve", "lisi");

        //流程启动
        ExecutionEntity pi1 = (ExecutionEntity) runtimeService.startProcessInstanceByKey("leave", map);

        List<Task> tq = taskService.createTaskQuery().taskAssignee("zhangsan").list();
        System.out.println(tq.size());
        String assignee = "zhangsan";//当前任务办理人
        List<Task> tasks = taskService//与任务相关的Service
                .createTaskQuery()//创建一个任务查询对象
                .taskAssignee(assignee)
                .list();
        if (tasks != null && tasks.size() > 0) {
            for (Task task : tasks) {
                System.out.println("任务ID:" + task.getId());
                System.out.println("任务的办理人:" + task.getAssignee());
                System.out.println("任务名称:" + task.getName());
                System.out.println("任务的创建时间:" + task.getCreateTime());

                System.out.println("流程实例ID:" + task.getProcessInstanceId());
                System.out.println("#####################################");
            }
        }

        System.out.println("method startActivityDemo end....");
        return false;

    }
}
